<template>
  <div class="digital-human-container">
    <!-- 顶部标题和按钮 -->
    <div class="header">
      <div class="app-title">
        <i class="el-icon-s-platform"></i>
        智能数字人面试系统
      </div>
      <el-button 
        type="primary" 
        @click="analyseResume" 
        :loading="isAnalysing"
        class="analyse-btn"
      >
        <i class="el-icon-s-data"></i> 一键解析简历
      </el-button>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 左侧：数字人区域 -->
      <div class="digital-human-block">
        <div class="block-title">3D角色</div>
        <div class="player-wrapper">
          <div ref="playerContainer" class="player-container"></div>
          <div v-if="!isPlayerActive" class="placeholder">
            <i class="el-icon-loading"></i>
            <p>数字人启动中...</p>
          </div>
        </div>

        <!-- 文本驱动区域 - 仅保留功能，不展示 -->
        <div class="text-driver" v-show="false">
          <el-input
            v-model="inputText"
            placeholder="输入要数字人说的内容"
            type="textarea"
            :rows="2"
            clearable
            class="driver-input"
          ></el-input>
          <el-button 
            type="primary" 
            @click="sendTextToAvatar" 
            :disabled="!isPlayerActive"
            class="send-btn"
          >
            <i class="el-icon-chat-line-round"></i> 发送
          </el-button>
        </div>
      </div>

      <!-- 中间区域 -->
      <div class="middle-column">
        <!-- 面试能力雷达图 -->
        <div class="interview-radar-block">
          <div class="block-title">面试能力雷达图</div>
          <div class="chart-container">
            <div v-if="hasInterviewData" ref="interviewRadarChart" class="chart"></div>
            <div v-else class="empty-placeholder">
              <i class="el-icon-info"></i>
              <p>暂无面试数据，请先完成面试</p>
            </div>
          </div>
        </div>
        
        <!-- 面试结果分析 -->
        <div class="interview-analysis-block">
          <div class="block-title">面试结果分析</div>
          <div v-if="hasInterviewData" class="analysis-content">
            <h3>面试综合评估报告</h3>
            <p>根据本次面试表现，您的能力评估如下：</p>
            
            <h4>优势领域：</h4>
            <ul>
              <li><strong>应变抗压能力</strong>：在压力测试环节表现优异，能够冷静思考并给出合理解决方案</li>
              <li><strong>沟通表达能力</strong>：语言表达清晰流畅，能够有效传达自己的想法</li>
            </ul>
            
            <h4>待提升领域：</h4>
            <ul>
              <li><strong>专业知识深度</strong>：对核心专业知识的掌握需要进一步加强</li>
              <li><strong>技术匹配度</strong>：部分技能与企业当前需求存在差距，建议针对性提升</li>
              <li><strong>逻辑思维能力</strong>：在复杂问题分析上可以进一步优化思考框架</li>
            </ul>
            
            <h4>发展建议：</h4>
            <p>建议在接下来的1-2个月内重点提升专业技术能力，尤其是前端框架的深度理解和项目实践。同时可参加逻辑思维训练课程，提升问题分析与解决能力。</p>
          </div>
          <div v-else class="empty-placeholder">
            <i class="el-icon-info"></i>
            <p>暂无面试数据，请先完成面试</p>
          </div>
        </div>
      </div>

      <!-- 右侧区域 -->
      <div class="right-column">
        <!-- 简历雷达图 -->
        <div class="resume-radar-block">
          <div class="block-title">简历雷达图</div>
          <div class="chart-container">
            <div v-if="showResumeData" ref="resumeRadarChart" class="chart"></div>
            <div v-else class="empty-placeholder">
              <i class="el-icon-info"></i>
              <p>暂无简历数据，请完成上传简历</p>
            </div>
          </div>
        </div>
        
        <!-- 简历分析报告 -->
        <div class="resume-report-block">
          <div class="block-title">简历分析报告</div>
          <div v-if="showResumeData" class="analysis-content">
            <MdPreview v-if="analysisResult" :modelValue="analysisResult" />
            <div v-else>
              <h3>简历综合评估报告</h3>
              <p>根据您的简历内容，评估如下：</p>
              
              <h4>优势领域：</h4>
              <ul>
                <li><strong>专业技能</strong>：熟练掌握Vue、React等主流前端框架，技术栈全面</li>
                <li><strong>项目经验</strong>：有多个完整项目开发经验，代码规范良好</li>
              </ul>
              
              <h4>待提升领域：</h4>
              <ul>
                <li><strong>算法基础</strong>：数据结构与算法基础需要加强</li>
                <li><strong>性能优化</strong>：对前端性能优化经验较少</li>
              </ul>
              
              <h4>改进建议：</h4>
              <p>建议加强算法训练，学习TypeScript提升代码质量，并参与更大规模项目积累经验。</p>
            </div>
          </div>
          <div v-else class="empty-placeholder">
            <i class="el-icon-info"></i>
            <p>暂无简历数据，请完成上传简历</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, nextTick, watch,toRefs } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import * as echarts from 'echarts'
import { useUserInformationStore } from '@/stores/canUserInformation'
import { useRoute } from 'vue-router'
import { MdPreview } from 'md-editor-v3'
import 'md-editor-v3/lib/preview.css'

// 定义 RTCPlayer 类型
interface IRTCPlayer {
  on: (event: string, callback: (...args: any[]) => void) => IRTCPlayer;
  resume: () => void;
  destroy: () => void;
  play: () => void;
  SetGlobalParams?: (params: any) => void;
  playerType?: number;
  stream?: any;
  videoSize?: any;
  container?: HTMLElement | null;
}

// 数字人状态
const isPlayerActive = ref(false)
const inputText = ref('')
const streamInfo = ref<any>(null)
const streamPolling = ref<any>(null)

// 简历分析相关状态
const isAnalysing = ref(false)
const radarData = ref<any>(null)
const interviewRadarChart = ref<HTMLElement | null>(null)
const resumeRadarChart = ref<HTMLElement | null>(null)
const interviewRadarInstance = ref<echarts.ECharts | null>(null)
const resumeRadarInstance = ref<echarts.ECharts | null>(null)
const analysisResult = ref<string>('')
const userStore = useUserInformationStore()
const route = useRoute()

// 面试数据状态
const hasInterviewData = ref(false)

// 记录是否已发送欢迎消息
const hasSentWelcome = ref(false)

// 是否显示简历数据
const showResumeData = ref(false)

// 背景res_key
const BACKGROUND_RES_KEY = "22SLM2teIw+aqR6Xsm2JbH6Ng310kDam2NiCY/RQ9n6s3nYJXloZWW1l64/g32vrn7d2lJQR7m9xD5EHYkVs145208ZzlALed5fXJBLgLg4tI+ItIrPB8y67oDnM0DlUnSbMKSZ2DnxdLF3ddbWYUNtAx2/SVhCs4ulm5khUJcH5ZE0N6JFb1MGDhwpFJx8sIPCRz4dxIqFDWC6Sntu2rDq7lyU/9tyCb9m2mFSr3nlqGBQ0nKFVF4MdjbbZH74dOpQ1lYZ0apoX4ae1Q9TYZnW9U7n+WWWxGep39VF73qLYIsTRdGv8QSe7aEB6s1XQQP19PdnMEVkH6f5ap5c00CKQfe8h05CHKHvsnQ3IB5A="

let player: IRTCPlayer | null = null
const playerContainer = ref<HTMLElement | null>(null)

const API_BASE = import.meta.env.VITE_API_BASE || 'http://localhost:8080'
const API_ENDPOINTS = {
  START: `${API_BASE}/api/avatar/start`,
  TEXT: `${API_BASE}/api/avatar/text`,
  STOP: `${API_BASE}/api/avatar/stop`,
  MESSAGE: `${API_BASE}/api/avatar/message`,
  SET_BACKGROUND: `${API_BASE}/api/avatar/setBackground`,
  ANALYSE_RESUME: `${API_BASE}/job/analyseResume`,
  CHECK_INTERVIEW: `${API_BASE}/job/userIsInterviewed`
};

// // 检查面试数据
// const checkInterviewData = async () => {
//   try {
//     const userInfo = userStore.getUserInfo();
//     const response = await axios.get(`${API_ENDPOINTS.CHECK_INTERVIEW}?userId=${userInfo.id}`);
    
//     if (response.data && response.data.code === 200) {
//       hasInterviewData.value = response.data.data;
//       if (hasInterviewData.value) {
//         initInterviewRadarChart();
//       }
//     }
//   } catch (error) {
//     console.error('检查面试数据失败:', error);
//     hasInterviewData.value = false;
//   }
// };

// 检查面试数据
const checkInterviewData = async () => {
  try {
    const userInfo = userStore.getUserInfo();
    const response = await axios.get(`${API_ENDPOINTS.CHECK_INTERVIEW}?userId=${userInfo.id}`);
    
    if (response.data && response.data.code === 200) {
      hasInterviewData.value = response.data.data;
      // 无论是否有数据，都初始化雷达图
      nextTick(() => {
        initInterviewRadarChart();
      });
    }
  } catch (error) {
    console.error('检查面试数据失败:', error);
    hasInterviewData.value = false;
    // 出错时也初始化雷达图
    nextTick(() => {
      initInterviewRadarChart();
    });
  }
};

// 监听路由变化，以触发欢迎消息
watch(() => route.query, (newQuery) => {
  if (newQuery.status && isPlayerActive.value && !hasSentWelcome.value) {
    console.log('检测到status参数:', newQuery.status);
    triggerWelcomeMessage(newQuery.status as string);
  }
}, { immediate: true });

// 触发欢迎消息
const triggerWelcomeMessage = (status: string) => {
  console.log('触发欢迎消息，状态:', status);

  let message = '';
  if (status === '0') {
    message = '登录成功，请到选择岗位页面，挑选心仪岗位，准备模拟面试';
    showResumeData.value = true;
    nextTick(() => {
      initResumeRadarChart();
    });
  } else if (status === '1') {
    message = '您的信息未完善，请在个人中心补全资料';
    showResumeData.value = false;
  }

  if (message && isPlayerActive.value) {
    console.log('准备发送消息:', message);
    inputText.value = message;
    sendTextToAvatar();
    hasSentWelcome.value = true;

    // 清除状态参数避免重复发送
    const newQuery = { ...route.query };
    delete newQuery.status;
    window.history.replaceState({}, '', `${route.path}?${new URLSearchParams(newQuery as any).toString()}`);
  } else {
    console.warn('无法发送消息:', { hasPlayer: !!player, isActive: isPlayerActive.value, message });
  }
}

// 组件挂载时自动启动数字人
onMounted(() => {
  startPlayer();
  checkInterviewData(); // 检查面试数据
});

// 组件卸载时自动停止数字人
onUnmounted(() => {
  stopPlayer();
  if (interviewRadarInstance.value) {
    interviewRadarInstance.value.dispose();
  }
  if (resumeRadarInstance.value) {
    resumeRadarInstance.value.dispose();
  }
});

// // 初始化面试能力雷达图
// const initInterviewRadarChart = () => {
//   if (!interviewRadarChart.value) return;

//   interviewRadarInstance.value = echarts.init(interviewRadarChart.value);

//   const option = {
//     title: {
//       left: 'center',
//       textStyle: {
//         color: '#333',
//         fontSize: 16
//       }
//     },
//     tooltip: {
//       trigger: 'item'
//     },
//     radar: {
//       indicator: [
//         { name: '专业知识水平', max: 100 },
//         { name: '技能匹配度', max: 100 },
//         { name: '应变抗压能力', max: 100 },
//         { name: '语音表达能力', max: 100 },
//         { name: '逻辑思维能力', max: 100 }
//       ],
//       radius: '65%',
//       splitNumber: 5,
//       axisName: {
//         color: '#666',
//         backgroundColor: '#fff',
//         borderRadius: 3,
//         padding: [3, 5]
//       },
//       splitLine: {
//         lineStyle: {
//           color: 'rgba(0, 0, 0, 0.1)'
//         }
//       },
//       splitArea: {
//         show: true,
//         areaStyle: {
//           color: ['rgba(64, 158, 255, 0.1)', 'rgba(64, 158, 255, 0.05)']
//         }
//       },
//       axisLine: {
//         lineStyle: {
//           color: 'rgba(0, 0, 0, 0.2)'
//         }
//       }
//     },
//     series: [{
//       name: '能力评估',
//       type: 'radar',
//       data: [{
//         value: [35, 40, 80, 65, 50],
//         name: '能力值',
//         symbol: 'circle',
//         symbolSize: 8,
//         lineStyle: {
//           width: 2,
//           color: '#5470C6'
//         },
//         areaStyle: {
//           color: new echarts.graphic.RadialGradient(0.5, 0.5, 1, [
//             { offset: 0, color: 'rgba(84, 112, 198, 0.5)' },
//             { offset: 1, color: 'rgba(84, 112, 198, 0.1)' }
//           ])
//         },
//         label: {
//           show: true,
//           formatter: '{c}',
//           position: 'top',
//           color: '#5470C6'
//         }
//       }]
//     }]
//   };

//   interviewRadarInstance.value.setOption(option);

//   // 响应式调整
//   window.addEventListener('resize', () => {
//     interviewRadarInstance.value?.resize();
//   });
// }

// 初始化面试能力雷达图
const initInterviewRadarChart = () => {
  if (!interviewRadarChart.value) return;

  // 如果已有实例，先销毁
  if (interviewRadarInstance.value) {
    interviewRadarInstance.value.dispose();
  }

  interviewRadarInstance.value = echarts.init(interviewRadarChart.value);

  const option = {
    title: {
      left: 'center',
      textStyle: {
        color: '#333',
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'item'
    },
    radar: {
      indicator: [
        { name: '专业知识水平', max: 100 },
        { name: '技能匹配度', max: 100 },
        { name: '应变抗压能力', max: 100 },
        { name: '语音表达能力', max: 100 },
        { name: '逻辑思维能力', max: 100 }
      ],
      radius: '65%',
      splitNumber: 5,
      axisName: {
        color: '#666',
        backgroundColor: '#fff',
        borderRadius: 3,
        padding: [3, 5]
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(0, 0, 0, 0.1)'
        }
      },
      splitArea: {
        show: true,
        areaStyle: {
          color: ['rgba(64, 158, 255, 0.1)', 'rgba(64, 158, 255, 0.05)']
        }
      },
      axisLine: {
        lineStyle: {
          color: 'rgba(0, 0, 0, 0.2)'
        }
      }
    },
    series: [{
      name: '能力评估',
      type: 'radar',
      data: hasInterviewData.value ? [{
        value: [35, 40, 80, 65, 50],
        name: '能力值',
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 2,
          color: '#5470C6'
        },
        areaStyle: {
          color: new echarts.graphic.RadialGradient(0.5, 0.5, 1, [
            { offset: 0, color: 'rgba(84, 112, 198, 0.5)' },
            { offset: 1, color: 'rgba(84, 112, 198, 0.1)' }
          ])
        },
        label: {
          show: true,
          formatter: '{c}',
          position: 'top',
          color: '#5470C6'
        }
      }] : []
    }]
  };

  interviewRadarInstance.value.setOption(option);

  // 响应式调整
  window.addEventListener('resize', () => {
    interviewRadarInstance.value?.resize();
  });
}

// 默认简历雷达图数据
const defaultRadarData = {
  professionalSkills: 85,
  workExperience: 78,
  teamwork: 82,
  problemSolving: 70,
  communication: 88
};

// 初始化简历雷达图
const initResumeRadarChart = () => {
  if (!resumeRadarChart.value) return;
  // 如果已有实例，先销毁
  if (resumeRadarInstance.value) {
    resumeRadarInstance.value.dispose();
  }
  resumeRadarInstance.value = echarts.init(resumeRadarChart.value);
  
  let seriesData: { value: number[] }[] = [];
  if (showResumeData.value && radarData.value) {
    // 使用从后端获取的数据
    const {professionalSkills, workExperience, teamwork, problemSolving, communication} = toRefs(radarData.value);
    seriesData = [{
      value: [
        professionalSkills.value,
        workExperience.value,
        teamwork.value,
        problemSolving.value,
        communication.value
      ]
    }];
  } else {
    // 使用默认数据
    seriesData = [{
      value: [
        defaultRadarData.professionalSkills,
        defaultRadarData.workExperience,
        defaultRadarData.teamwork,
        defaultRadarData.problemSolving,
        defaultRadarData.communication
      ]
    }];
  }

  const option = {
    title: {
      left: 'center',
      textStyle: {
        color: '#333',
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'item'
    },
    radar: {
      indicator: [
        { name: '专业技能', max: 100 },
        { name: '项目经验', max: 100 },
        { name: '团队协作', max: 100 },
        { name: '问题解决', max: 100 },
        { name: '沟通能力', max: 100 }
      ],
      radius: '65%',
      splitNumber: 5,
      axisName: {
        color: '#666',
        backgroundColor: '#fff',
        borderRadius: 3,
        padding: [3, 5]
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(0, 0, 0, 0.1)'
        }
      },
      splitArea: {
        show: true,
        areaStyle: {
          color: ['rgba(58, 191, 156, 0.1)', 'rgba(58, 191, 156, 0.05)']
        }
      },
      axisLine: {
        lineStyle: {
          color: 'rgba(0, 0, 0, 0.2)'
        }
      }
    },
    series: [{
      name: '能力评估',
      type: 'radar',
      data: seriesData
    }]
  };
  resumeRadarInstance.value.setOption(option);
  // 响应式调整
  window.addEventListener('resize', () => {
    resumeRadarInstance.value?.resize();
  });
}

// 启动数字人
const startPlayer = async () => {
  try {
    console.log('正在启动数字人...');
    const response = await axios.post(`${API_ENDPOINTS.START}?round=4`);

    if (response.status === 200) {
      isPlayerActive.value = true;
      console.log('数字人启动API调用成功');

      // 启动轮询获取推流信息
      startPollingStreamInfo();

      // 检查是否有状态参数需要处理
      if (route.query.status && !hasSentWelcome.value) {
        console.log('检测到初始status参数:', route.query.status);
        setTimeout(() => {
          triggerWelcomeMessage(route.query.status as string);
        }, 2000); // 延迟2秒确保播放器初始化
      }
    }
  } catch (error: any) {
    console.error('启动数字人失败:', error);
    ElMessage.error('数字人启动失败，请刷新页面重试');
  }
}

// 发送文本到数字人
const sendTextToAvatar = async () => {
  if (!inputText.value.trim()) {
    ElMessage.warning('请输入要发送的文本');
    return;
  }

  try {
    console.log('正在发送文本到数字人:', inputText.value);
    const response = await axios.post(
      `${API_ENDPOINTS.TEXT}?round=4`,
      inputText.value,
      {
        headers: { 'Content-Type': 'text/plain' }
      }
    );

    if (response.status === 200) {
      console.log('文本发送成功');
      inputText.value = '';
    }
  } catch (error: any) {
    console.error('发送文本失败:', error);
    ElMessage.error('消息发送失败');
  }
}

// 设置背景
const setBackground = async () => {
  try {
    console.log('正在设置数字人背景...');
    await axios.post(API_ENDPOINTS.SET_BACKGROUND, {
      type: 'res_key',
      data: BACKGROUND_RES_KEY
    });

    if (player && player.SetGlobalParams) {
      player.SetGlobalParams({
        background: {
          type: 'res_key',
          data: BACKGROUND_RES_KEY
        }
      });
    }
    console.log('背景设置成功');
  } catch (error: any) {
    console.error('设置背景失败', error);
  }
}

// 解析推流信息
const parseStreamInfo = (message: any) => {
  try {
    let data = message;
    if (typeof message === 'string') {
      try {
        data = JSON.parse(message);
      } catch (parseError) {
        console.error('JSON解析失败:', parseError);
        throw new Error('无效的JSON字符串');
      }
    }

    if (typeof data !== 'object' || data === null) {
      throw new Error('推流信息必须是对象');
    }

    const avatarPayload = data.payload?.avatar;
    if (!avatarPayload) {
      throw new Error('推流信息缺少avatar字段');
    }

    const streamUrl = avatarPayload.stream_url;
    const userSign = avatarPayload.stream_extend?.user_sign;
    const appid = avatarPayload.stream_extend?.appid;

    if (!streamUrl || !userSign) {
      throw new Error('推流信息不完整');
    }

    let urlStr = streamUrl;
    if (urlStr.startsWith('xrtcs://')) {
      urlStr = 'https://' + urlStr.substring(8);
    } else if (urlStr.startsWith('xrtc://')) {
      urlStr = 'http://' + urlStr.substring(7);
    }

    const url = new URL(urlStr);
    const server = `${url.protocol}//${url.host}`;
    const roomId = url.pathname.split('/').pop() || '';
    const userId = `user_${Math.random().toString(36).substr(2, 9)}`;

    return {
      sid: avatarPayload.cid || `vms_${Date.now()}`,
      server,
      auth: userSign,
      appid: appid || "1000000001",
      userId,
      roomId,
      timeStr: Date.now().toString(),
    };
  } catch (error) {
    console.error('解析推流信息失败:', error);
    return null;
  }
};

// 获取推流信息
const fetchStreamInfo = async () => {
  try {
    const response = await axios.get(API_ENDPOINTS.MESSAGE);

    if (response.data && response.data !== "No message received yet") {
      const info = parseStreamInfo(response.data);

      if (info) {
        console.log('获取到推流信息:', info);
        streamInfo.value = info;
        return true;
      }
    }
    return false;
  } catch (error: any) {
    console.error('获取推流信息失败:', error);
    return false;
  }
};

// 启动轮询获取推流信息
const startPollingStreamInfo = () => {
  clearInterval(streamPolling.value);
  console.log('开始轮询推流信息...');

  streamPolling.value = setInterval(async () => {
    const success = await fetchStreamInfo();

    if (success) {
      clearInterval(streamPolling.value);
      initPlayer();
    }
  }, 1000);
};

// 初始化播放器
const initPlayer = () => {
  if (!playerContainer.value) {
    console.error('播放器容器未找到');
    return;
  }

  try {
    console.log('正在初始化播放器...');
    import("@/utils/rtcplayer2.1.3/rtcplayer.esm.js").then(({ RTCPlayer }) => {
      player = new RTCPlayer({}) as unknown as IRTCPlayer;

      player
        .on('play', () => {
          console.log('播放器已启动');
          setBackground();

          // 再次检查状态参数（双保险）
          if (route.query.status && !hasSentWelcome.value) {
            console.log('播放器就绪后检测到status参数:', route.query.status);
            setTimeout(() => {
              triggerWelcomeMessage(route.query.status as string);
            }, 1000);
          }
        })
        .on('playing', () => console.log('数字人播放中'))
        .on('error', (e: any) => console.error(`播放器错误: ${e.message || e}`));

      (player as any).playerType = 12;

      if (streamInfo.value) {
        (player as any).stream = streamInfo.value;
      } else {
        (player as any).stream = {
          sid: "vms000ec4da@dx195f094539d6f19882",
          server: "https://xrtc-cn-east-2.xf-yun.com   ",
          auth: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiIxMDAwMDAwMDAxIiwidGltZSI6MTY0ODAxODQ2MTU0MywiaWF0IjoxNjQ4MTkxMjQyfQ.CTcOh_kCLqvvglo5VLVnjgpZzoFpzk7Un3Et0c9dhUs",
          appid: "1000000001",
          userId: "123123123",
          roomId: "ase0001bbe2hu19632f0f6070442142",
          timeStr: Date.now().toString(),
        };
      }

      (player as any).videoSize = { width: 480, height: 853 };
      (player as any).container = playerContainer.value;

      player.play();
    });
  } catch (e) {
    console.error('播放器初始化失败', e);
  }
};

// 停止数字人
const stopPlayer = async () => {
  try {
    if (player) {
      player.destroy();
      player = null;
    }

    await axios.post(API_ENDPOINTS.STOP);
    clearInterval(streamPolling.value);

    isPlayerActive.value = false;
    console.log('数字人已停止');
  } catch (error: any) {
    console.error('停止数字人失败', error);
  }
}

// 解析简历
const analyseResume = async () => {
  isAnalysing.value = true;
  radarData.value = null;
  analysisResult.value = '';
  try {
    const userInfo = userStore.getUserInfo();
    const url = `${API_ENDPOINTS.ANALYSE_RESUME}?userId=${userInfo.id}`;
    const response = await axios.get(url);
    if (response.data && response.data.data) {
      radarData.value = response.data.data; // 更新雷达图数据
      showResumeData.value = true; // 标识简历数据已准备好
      analysisResult.value = response.data.data.evaluation;
      nextTick(() => {
        initResumeRadarChart(); // 重新初始化雷达图以应用新的数据
      });
    }
  } catch (error) {
    console.error('解析简历失败', error);
    ElMessage.error('解析简历失败，请重试');
  } finally {
    isAnalysing.value = false;
  }
};
</script>

<style scoped>
.digital-human-container {
  display: flex;
  flex-direction: column;
  height: 90vh;
  background: #f0f2f5;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.app-title {
  font-size: 24px;
  font-weight: 600;
  color: #1a73e8;
  display: flex;
  align-items: center;
}

.app-title i {
  margin-right: 10px;
  font-size: 28px;
}

.main-content {
  display: flex;
  gap: 20px;
  flex: 1;
  overflow: hidden;
}

/* 左侧：数字人区域 */
.digital-human-block {
  flex: 0 0 30%;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  position: relative;
}

.block-title {
  position: absolute;
  top: 0;
  left: 0;
  background: #16a085;
  color: white;
  padding: 8px 15px;
  font-size: 14px;
  font-weight: 500;
  z-index: 10;
  border-bottom-right-radius: 8px;
}

.player-wrapper {
  flex: 1;
  position: relative;
  background: linear-gradient(135deg, #1a2a6c, #b21f1f, #1a2a6c);
}

.player-container {
  width: 100%;
  height: 100%;
  background: transparent;
}

.placeholder {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: rgba(255, 255, 255, 0.85);
}

.placeholder i {
  font-size: 48px;
  margin-bottom: 15px;
  animation: rotating 2s linear infinite;
}

.placeholder p {
  font-size: 18px;
}

.text-driver {
  margin-top: 20px;
  display: flex;
  gap: 10px;
  width: 480px;
}

.driver-input {
  flex: 1;
}

.send-btn {
  height: auto;
  padding: 12px 24px;
}

/* 中间区域 */
.middle-column {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.interview-radar-block,
.interview-analysis-block {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  position: relative;
  overflow: hidden;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.interview-analysis-block {
  padding: 0;
}

/* 图表容器 */
.chart-container {
  flex: 1;
  padding: 20px 15px;
  position: relative;
}

.chart {
  width: 100%;
  height: 100%;
}

/* 空状态提示 */
.empty-placeholder {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #909399;
  text-align: center;
}

.empty-placeholder i {
  font-size: 48px;
  margin-bottom: 15px;
}

.empty-placeholder p {
  font-size: 18px;
  margin: 0;
}

/* 右侧区域 */
.right-column {
  flex: 0 0 30%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.resume-radar-block,
.resume-report-block {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  position: relative;
  overflow: hidden;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.resume-report-block {
  padding: 0;
}

/* 分析内容样式 */
.analysis-content {
  margin-top: 20px;
  line-height: 1.8;
  text-align: left;
  padding: 20px;
  height: calc(100% - 40px);
  overflow-y: auto;
}

.analysis-content h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #333;
  text-align: center;
}

.analysis-content h4 {
  margin: 15px 0 8px;
  color: #1a73e8;
}

.analysis-content ul {
  padding-left: 20px;
  margin-bottom: 15px;
}

.analysis-content li {
  margin-bottom: 5px;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>